package cn.iocoder.yudao.module.diy.service.diy;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.diy.controller.admin.diy.vo.other.StartUpPageConfigVo;
import cn.iocoder.yudao.module.diy.controller.app.diy.param.DiyInfoParam;
import cn.iocoder.yudao.module.diy.controller.app.diy.param.DiyShareParam;
import cn.iocoder.yudao.module.diy.controller.app.diy.param.DiyTabbarListParam;
import cn.iocoder.yudao.module.diy.controller.app.diy.param.DiyTabbarParam;
import cn.iocoder.yudao.module.diy.dal.dataobject.page.PageDO;
import cn.iocoder.yudao.module.diy.dal.dataobject.route.RouteDO;
import cn.iocoder.yudao.module.diy.dal.diy.BottomConfigVo;
import cn.iocoder.yudao.module.diy.dal.diy.PagesEnum;
import cn.iocoder.yudao.module.diy.dal.diy.TemplateParam;
import cn.iocoder.yudao.module.diy.dal.mysql.page.PageMapper;
import cn.iocoder.yudao.module.diy.dal.mysql.route.RouteMapper;
import cn.iocoder.yudao.module.diy.enums.TemplateEnum;
import cn.iocoder.yudao.module.diy.dal.diy.DiyInfoVo;
import cn.iocoder.yudao.module.diy.dal.diy.DiyTabbarVo;
import cn.iocoder.yudao.module.diy.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class DiyAppServiceImpl implements IDiyAppService {

    @Autowired
    private PageMapper pageMapper;

    @Autowired
    private RouteMapper routeMapper;

    @Resource
    private ICoreDiyConfigService coreDiyConfigService;

//    @Resource
//    private ICoreSiteService coreSiteService;

    @Override
    public Object info(DiyInfoParam param) {
        Integer id = ObjectUtil.defaultIfNull(param.getId(), 0);
        String name = ObjectUtil.defaultIfNull(param.getName(), "");
//        if (StringUtils.isNotEmpty(param.getAddonName())) {
//            StringBuilder stringBuilder = new StringBuilder(name);
//            stringBuilder.insert(4, param.getAddonName() + "_");
//            String modifiedString = stringBuilder.toString();
//            name=modifiedString.toUpperCase();
//        }

        log.info("id: {}, name: {}", id, name);

        StartUpPageConfigVo startUpPage = null;
        JSONObject template = null;

        if (!StrUtil.isEmpty(name)) {
            // 查询启动页
            startUpPage = coreDiyConfigService.getStartUpPageConfig(param.tenantId().longValue(), name);
            log.info("startUpPage: {}", JSONUtil.toJsonStr(startUpPage));

            TemplateParam templateParam = new TemplateParam();
            String[] key = { name };
            templateParam.setKey(key);
            template = TemplateEnum.getTemplate(templateParam).getJSONObject(name);
        }

        if (id == 0 && startUpPage != null && template != null && !startUpPage.getPage().equals(template.getStr("page"))) {
            log.info("enter if, template: {}", template.toString());
            return startUpPage;
        } else {
            QueryWrapper<PageDO> queryWrapper = new QueryWrapper();
            log.info("site_id: {}",param.tenantId() );

            PageDO info = null;

            log.info("id: {}, name: {}", id, name);
            if (id > 0) {
//                queryWrapper.eq("id", id);
                queryWrapper.eq("page_name", name);
                info = pageMapper.selectOne(queryWrapper);
            } else if (!name.isEmpty()) {
                queryWrapper.eq("page_name", name);
                queryWrapper.eq("is_default", 1);
                info = pageMapper.selectOne(queryWrapper);
            }

            log.info("info: {}", JSONUtil.toJsonStr(info));

            if (info == null) {
                if (!name.isEmpty()) {
                    JSONObject pageData = getFirstPageData(name, "");
                    if (pageData != null) {
                        info = JSONUtil.toBean(pageData, PageDO.class);
                        info.setPageValue(info.getTemplate());
                        info.setId(param.tenantId().longValue());
                    }
                }
            }

            log.info("info: {}", JSONUtil.toJsonStr(info));
            if (info == null)  return null;

            DiyInfoVo vo = new DiyInfoVo();
            BeanUtils.copyProperties(info, vo);
            vo.setName(info.getPageName());
            vo.setTitle(info.getPageTitle());
            vo.setValue(info.getPageValue());
            vo.setType(info.getPageType());
            log.info("vo: {}", JSONUtil.toJsonStr(vo));
            return vo;
        }
    }

    /**
     * 获取默认页面数据
     * @param type
     * @param addon
     * @return
     */
    public JSONObject getFirstPageData(String type, String addon) {
        JSONObject pages = PagesEnum.getPagesByAddon(type);
        if (pages == null || pages.keySet().size() == 0) return null;

        JSONObject data = new JSONObject();
        data.set("type", type);
        data.set("template", pages.getJSONObject(pages.keySet().iterator().next()));
        JSONObject template=pages.getJSONObject(pages.keySet().iterator().next());
        data.set("value",template.getJSONObject("data"));
        data.set("title","title");
        return data;
    }


    @Override
    public DiyTabbarVo tabbar(DiyTabbarParam param) {
        DiyTabbarVo diyTabbarVo = null;
        return diyTabbarVo;
    }

    @Override
    public List<BottomConfigVo> tabbarList(DiyTabbarListParam param) {
        List<BottomConfigVo> list = coreDiyConfigService.getBottomList();
//        SiteInfoVo site = coreSiteService.getSiteCache(param.tenantId());

        List<BottomConfigVo> tabbarList = new LinkedList<>();
        for (BottomConfigVo item : list) {

            BottomConfigVo config = coreDiyConfigService.getBottomConfig(param.tenantId().longValue(), item.getKey());
            tabbarList.add(config);
        }

        return tabbarList;
    }

    @Override
    public JSONObject share(DiyShareParam param) {
        QueryWrapper<RouteDO> queryWrapper = new QueryWrapper();
        queryWrapper.select("id,title,route_name,page,share,is_share");
        queryWrapper.eq("page", param.getRoute());
        queryWrapper.eq("site_id", param.tenantId());

        RouteDO diyRoute = routeMapper.selectOne(queryWrapper);
        if (diyRoute == null || diyRoute.getShare().isEmpty()) return new JSONObject();

        JSONObject share = JSONUtil.parseObj(diyRoute.getShare());
        share.set("route", diyRoute.getPage());
        share.set("query", "");

        JSONObject query = new JSONObject();

        if (param.getParams() != null && !param.getParams().isEmpty()) {
            query = JSONUtil.parseObj(param.getParams());
        }

        if (param.memberId() != null && param.memberId() > 0) {
            query.set("mid", param.memberId());
        }

        String queryStr = "";
        if (query.keySet().size() > 0) {
            for (String key: query.keySet()) {
                queryStr += queryStr.isEmpty() ? key + "=" + query.getStr(key) : "&" + key + "=" + query.getStr(key);
            }
        }
        share.set("url", share.getStr("route") + (queryStr.isEmpty() ? "" : "?" + queryStr));

        return share;
    }

}
